// wsService.ts
import { defineStore } from 'pinia'

export default defineStore('ws', {
  state: () => ({
    ws: null,
    isConnected: false,
    receivedMessages: [],
    wsUrl: 'wss://ws.ifelse.io',
    reconnectInterval: 3000,
    reconnectTimer: null,
  }),

  actions: {
    connectWS() {
      if (this.ws && this.isConnected) {
        console.log('✅ 已连接 WebSocket')
        return
      }

      if (this.ws) {
        this.disconnect()
      }

      this.ws = new WebSocket(this.wsUrl)

      this.ws.onopen = () => {
        console.log('✅ WebSocket 连接成功')
        this.isConnected = true
      }

      this.ws.onmessage = (event) => {
        try {
          const data = event.data
          this.receivedMessages.push({
            data,
            time: new Date(),
          })
          console.log('📩 收到消息', data)
        } catch (e) {
          console.error('❗WebSocket 消息解析失败', e)
        }
      }

      this.ws.onerror = (err) => {
        console.error('❗WebSocket 错误', err)
      }

      this.ws.onclose = () => {
        console.warn('🔌 WebSocket 已断开')
        this.isConnected = false
        this.tryReconnect()
      }
    },

    send(data) {
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        console.warn('❗WebSocket 未连接，无法发送消息')
        return
      }

      try {
        const message = typeof data === 'string' ? data : JSON.stringify(data)
        this.ws.send(message)
        console.log('🚀 发送消息:', message)
      } catch (e) {
        console.error('❗发送失败:', e)
      }
    },

    disconnect() {
      if (this.ws) {
        this.ws.close()
        this.ws = null
        this.isConnected = false
        if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
        console.log('🛑 WebSocket 已断开')
      }
    },

    tryReconnect() {
      if (this.reconnectTimer) return
      console.log(`🔄 准备 ${this.reconnectInterval / 1000}s 后重连 WebSocket...`)
      this.reconnectTimer = window.setTimeout(() => {
        this.reconnectTimer = null
        this.connectWS()
      }, this.reconnectInterval)
    },
  },
})
